from flask import render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from . import admin
from ..models import User, Couple, Comment, Quote, Vote, CommentLike
from .. import db
from .forms import CoupleForm, QuoteForm, UserEditForm
from functools import wraps
from werkzeug.security import generate_password_hash
import os
from werkzeug.utils import secure_filename
from flask import current_app
import time
from ..utils import save_image, delete_file
from zhipuai import ZhipuAI

# 在文件开头添加配置
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
UPLOAD_FOLDER = 'app/static/uploads'

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def save_avatar(file, user_type):
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        # 生成唯一文件名
        unique_filename = f"{user_type}_{int(time.time())}_{filename}"
        if not os.path.exists(UPLOAD_FOLDER):
            os.makedirs(UPLOAD_FOLDER)
        file_path = os.path.join(UPLOAD_FOLDER, unique_filename)
        file.save(file_path)
        return f'/static/uploads/{unique_filename}'
    return None

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_admin:
            flash('需要管理员权限')
            return redirect(url_for('main.index'))
        return f(*args, **kwargs)
    return decorated_function

@admin.route('/')
@login_required
@admin_required
def index():
    users_count = User.query.count()
    couples_count = Couple.query.count()
    comments_count = Comment.query.count()
    votes_count = Vote.query.count()
    
    return render_template('admin/index.html',
                         users_count=users_count,
                         couples_count=couples_count,
                         comments_count=comments_count,
                         votes_count=votes_count)

@admin.route('/users')
@login_required
@admin_required
def manage_users():
    page = request.args.get('page', 1, type=int)
    users = User.query.paginate(page=page, per_page=20)
    return render_template('admin/users.html', users=users)

@admin.route('/couples', methods=['GET', 'POST'])
@login_required
@admin_required
def manage_couples():
    form = CoupleForm()
    if form.validate_on_submit():
        couple = Couple(
            season=form.season.data,
            husband_name=form.husband_name.data,
            husband_age=form.husband_age.data,
            husband_occupation=form.husband_occupation.data,
            wife_name=form.wife_name.data,
            wife_age=form.wife_age.data,
            wife_occupation=form.wife_occupation.data,
            marriage_years=form.marriage_years.data,
            story=form.story.data
        )
        
        # 处理丈夫头像
        if form.husband_avatar.data:
            avatar_path = save_image(form.husband_avatar.data, 'husbands')
            if avatar_path:
                couple.husband_avatar = avatar_path
                
        # 处理妻子头像
        if form.wife_avatar.data:
            avatar_path = save_image(form.wife_avatar.data, 'wives')
            if avatar_path:
                couple.wife_avatar = avatar_path
        
        try:
            db.session.add(couple)
            db.session.commit()
            flash('夫妻信息添加成功')
            return redirect(url_for('admin.manage_couples'))
        except Exception as e:
            db.session.rollback()
            flash('添加失败，请稍后重试')
            return render_template('admin/couples.html', form=form, couples=Couple.query.order_by(Couple.season.desc()).all())
    
    # 获取所有夫妻信息，按季数倒序排列
    couples = Couple.query.order_by(Couple.season.desc()).all()
    return render_template('admin/couples.html', couples=couples, form=form)

@admin.route('/quotes', methods=['GET', 'POST'])
@login_required
@admin_required
def manage_quotes():
    form = QuoteForm()
    if form.validate_on_submit():
        quote = Quote(
            content=form.content.data,
            author=form.author.data,
            is_active=form.is_active.data
        )
        db.session.add(quote)
        db.session.commit()
        flash('名言添加成功')
        return redirect(url_for('admin.manage_quotes'))
    
    quotes = Quote.query.all()
    return render_template('admin/quotes.html', quotes=quotes, form=form)

@admin.route('/users/<int:id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_user(id):
    user = User.query.get_or_404(id)
    form = UserEditForm(original_username=user.username, 
                       original_email=user.email, 
                       obj=user)
    
    if form.validate_on_submit():
        user.username = form.username.data
        user.email = form.email.data
        if form.password.data:
            user.password_hash = generate_password_hash(form.password.data)
        user.is_admin = form.is_admin.data
        
        try:
            db.session.commit()
            flash('用户信息已更新')
            return redirect(url_for('admin.manage_users'))
        except Exception as e:
            db.session.rollback()
            flash('更新失败，请稍后重试')
            
    return render_template('admin/edit_user.html', form=form, user=user)

@admin.route('/users/<int:id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_user(id):
    user = User.query.get_or_404(id)
    if user == current_user:
        return jsonify({'error': '不能删除当前登录的用户'}), 400
    
    db.session.delete(user)
    db.session.commit()
    return jsonify({'success': True})

@admin.route('/couples/<int:id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_couple(id):
    couple = Couple.query.get_or_404(id)
    form = CoupleForm(obj=couple)
    
    if form.validate_on_submit():
        couple.season = form.season.data
        couple.husband_name = form.husband_name.data
        couple.husband_age = form.husband_age.data
        couple.husband_occupation = form.husband_occupation.data
        couple.wife_name = form.wife_name.data
        couple.wife_age = form.wife_age.data
        couple.wife_occupation = form.wife_occupation.data
        couple.marriage_years = form.marriage_years.data
        couple.story = form.story.data
        
        # 处理丈夫头像
        if form.husband_avatar.data:
            # 删除旧头像
            if couple.husband_avatar:
                delete_file(couple.husband_avatar)
            # 保存新头像
            avatar_path = save_image(form.husband_avatar.data, 'husbands')
            if avatar_path:
                couple.husband_avatar = avatar_path
                
        # 处理妻子头像
        if form.wife_avatar.data:
            # 删除旧头像
            if couple.wife_avatar:
                delete_file(couple.wife_avatar)
            # 保存新头像
            avatar_path = save_image(form.wife_avatar.data, 'wives')
            if avatar_path:
                couple.wife_avatar = avatar_path
            
        db.session.commit()
        flash('夫妻信息已更新')
        return redirect(url_for('admin.manage_couples'))
        
    return render_template('admin/edit_couple.html', form=form, couple=couple)

@admin.route('/quotes/<int:id>/edit', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_quote(id):
    quote = Quote.query.get_or_404(id)
    form = QuoteForm(obj=quote)
    
    if form.validate_on_submit():
        quote.content = form.content.data
        quote.author = form.author.data
        quote.is_active = form.is_active.data
        
        db.session.commit()
        flash('名言已更新')
        return redirect(url_for('admin.manage_quotes'))
        
    return render_template('admin/edit_quote.html', form=form, quote=quote)

@admin.route('/couples/<int:id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_couple(id):
    couple = Couple.query.get_or_404(id)
    
    # 删除头像文件
    if couple.husband_avatar:
        delete_file(couple.husband_avatar)
    if couple.wife_avatar:
        delete_file(couple.wife_avatar)
    
    db.session.delete(couple)
    db.session.commit()
    return jsonify({'success': True})

@admin.route('/quotes/<int:id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_quote(id):
    quote = Quote.query.get_or_404(id)
    db.session.delete(quote)
    db.session.commit()
    return jsonify({'success': True})

@admin.route('/comments')
@login_required
@admin_required
def manage_comments():
    page = request.args.get('page', 1, type=int)
    status = request.args.get('status', 'all')
    
    query = Comment.query
    if status == 'hidden':
        query = query.filter_by(is_hidden=True)
    elif status == 'active':
        query = query.filter_by(is_hidden=False)
        
    comments = query.order_by(Comment.timestamp.desc()).paginate(
        page=page, per_page=20, error_out=False)
    
    return render_template('admin/comments.html', comments=comments)

@admin.route('/comments/<int:id>/toggle', methods=['POST'])
@login_required
@admin_required
def toggle_comment(id):
    comment = Comment.query.get_or_404(id)
    comment.is_hidden = not comment.is_hidden
    db.session.commit()
    return jsonify({
        'success': True,
        'is_hidden': comment.is_hidden
    })

@admin.route('/comments/<int:id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_comment(id):
    comment = Comment.query.get_or_404(id)
    db.session.delete(comment)
    db.session.commit()
    return jsonify({'success': True})

@admin.route('/users/add', methods=['GET', 'POST'])
@login_required
@admin_required
def add_user():
    form = UserEditForm()
    if form.validate_on_submit():
        # 检查用户名是否已存在
        if User.query.filter_by(username=form.username.data).first():
            flash('该用户名已被使用')
            return render_template('admin/add_user.html', form=form)
        
        # 检查邮箱是否已存在
        if User.query.filter_by(email=form.email.data).first():
            flash('该邮箱已被注册')
            return render_template('admin/add_user.html', form=form)
        
        try:
            user = User(
                username=form.username.data,
                email=form.email.data,
                is_admin=form.is_admin.data
            )
            if form.password.data:
                user.password_hash = generate_password_hash(form.password.data)
            db.session.add(user)
            db.session.commit()
            flash('用户添加成功')
            return redirect(url_for('admin.manage_users'))
        except Exception as e:
            db.session.rollback()
            flash('添加失败，请稍后重试')
            return render_template('admin/add_user.html', form=form)
            
    return render_template('admin/add_user.html', form=form)

@admin.route('/couple/<int:id>/reset_votes', methods=['POST'])
@login_required
@admin_required
def reset_votes(id):
    couple = Couple.query.get_or_404(id)
    # 删除所有投票
    Vote.query.filter_by(couple_id=couple.id).delete()
    db.session.commit()
    return jsonify({'success': True})

@admin.route('/couple/<int:id>/reset_likes', methods=['POST'])
@login_required
@admin_required
def reset_likes(id):
    couple = Couple.query.get_or_404(id)
    couple.likes_count = 0
    db.session.commit()
    return jsonify({'success': True})

@admin.route('/comment/<int:id>/reset_likes', methods=['POST'])
@login_required
@admin_required
def reset_comment_likes(id):
    try:
        comment = Comment.query.get_or_404(id)
        # 删除所有点赞记录
        CommentLike.query.filter_by(comment_id=comment.id).delete()
        # 重置点赞数
        comment.likes_count = 0
        db.session.commit()
        return jsonify({'success': True})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@admin.route('/couple/<int:id>/set_likes', methods=['POST'])
@login_required
@admin_required
def set_likes(id):
    couple = Couple.query.get_or_404(id)
    data = request.get_json()
    likes_count = data.get('likes_count', 0)
    
    if not isinstance(likes_count, int) or likes_count < 0:
        return jsonify({'error': '无效的点赞数'}), 400
        
    couple.likes_count = likes_count
    db.session.commit()
    return jsonify({'success': True})

@admin.route('/couple/<int:id>/set_votes', methods=['POST'])
@login_required
@admin_required
def set_votes(id):
    couple = Couple.query.get_or_404(id)
    data = request.get_json()
    stay_votes = data.get('stay_votes', 0)
    divorce_votes = data.get('divorce_votes', 0)
    
    if not all(isinstance(x, int) and x >= 0 for x in [stay_votes, divorce_votes]):
        return jsonify({'error': '无效的投票数'}), 400
    
    # 删除所有现有投票
    Vote.query.filter_by(couple_id=couple.id).delete()
    
    # 添加新的投票
    for _ in range(stay_votes):
        vote = Vote(couple=couple, vote_type='stay_together')
        db.session.add(vote)
    
    for _ in range(divorce_votes):
        vote = Vote(couple=couple, vote_type='divorce')
        db.session.add(vote)
    
    db.session.commit()
    return jsonify({'success': True})

@admin.route('/stats')
@login_required
@admin_required
def manage_stats():
    couples = Couple.query.order_by(Couple.season.desc()).all()
    return render_template('admin/manage_stats.html', couples=couples)

@admin.route('/couple/<int:id>/check_comments')
@login_required
@admin_required
def check_comments(id):
    couple = Couple.query.get_or_404(id)
    has_comments = couple.comments.filter_by(is_hidden=False).count() > 0
    return jsonify({'has_comments': has_comments})

@admin.route('/couple/<int:id>/ai_summary', methods=['POST'])
@login_required
@admin_required
def ai_summary(id):
    couple = Couple.query.get_or_404(id)
    
    # 获取前100条评论
    comments = couple.comments.filter_by(is_hidden=False).order_by(Comment.timestamp.desc()).limit(100).all()
    comments_text = "\n".join([f"{c.author.username}: {c.content}" for c in comments])
    
    try:
        # 配置智谱AI
        client = ZhipuAI(api_key="xxx") #这里填写apikey QQ：575732022
        
        response = client.chat.completions.create(
            model="glm-4-plus",
            messages=[
                {"role": "system", "content": "你是一个专业的评论区情感分析师，善于总结和分析网友对情侣关系的评论。请对以下评论进行分析和总结，总结出来的内容就是评论，我要直接发布，重点关注：1. 网友对这对情侣的整体态度 2. 主要讨论的问题和焦点 3. 对这段关系的建议。请用温和专业的语气进行总结。"},
                {"role": "user", "content": f"请分析总结以下评论：\n{comments_text}"}
            ]
        )
        
        summary = response.choices[0].message.content
        return jsonify({'summary': summary})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500